package com.lmt.feign;

import com.lmt.entity.User;
import feign.hystrix.FallbackFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;

/**
 * Date 2018/06/28
 *
 * @author MT-Lin
 */
// Feign禁用Hystrix
// @FeignClient(name = "provider", configuration = FeignDisableHystrixConfiguration.class)
// 获取出错原因
// @FeignClient(name = "provider", fallbackFactory = ProviderFeignClient.ProviderFeignClientFallbackFactory.class)
@FeignClient(name = "provider", fallback = ProviderFeignClient.ProviderFeignClientFallback.class)
public interface ProviderFeignClient {

    Logger logger = LoggerFactory.getLogger(ProviderFeignClient.class);

    @RequestMapping(value = "/findUserById", method = RequestMethod.GET)
    User findUserById(@RequestParam(name = "id") String id);

    // 使用fallback属性，为Feign添加调用失败处理，无法获得失败原因
    @Component
    class ProviderFeignClientFallback implements ProviderFeignClient{

        @Override
        public User findUserById(String id) {
            return new User();
        }
    }

    // 使用fallbackFactory属性，为Feign添加回退，并获得失败原因
    @Component
    class ProviderFeignClientFallbackFactory implements FallbackFactory<ProviderFeignClient> {

        @Override
        public ProviderFeignClient create(Throwable throwable) {
            return id -> {
                logger.error("com.lmt.feign.ProviderFeignClient.findUserById fallback reason:{}", throwable.toString());
                User user = new User();
                user.setGmtCreate(new Date());
                user.setUserName("DefaultUserName");
                return user;
            };
        }
    }
}
